<template>
  <a-modal
    :maskClosable="false"
    centered
    width="800px"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :title="deptMemberOpt"
    :destroyOnClose="true"
    @ok="handleOk2"
    @cancel="handleCancel2"
  >
    <a-row :gutter="[100, 10]">
      <a-form-model
        layout="vertical"
        ref="ruleForm2"
        :model="form"
        :rules="rules2"
        style="padding: 20px"
      >
        <a-col :span="12">
          <a-form-model-item prop="account" label="账号（手机号）">
            <a-input v-model="form.account" :max-length="11" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="password" label="密码">
            <a-input v-model="defaultPh" disabled />
          </a-form-model-item>
        </a-col>

        <a-col :span="12">
          <a-form-model-item prop="status" label="账号状态">
            <a-select v-model="form.status" :default-value="1">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">冻结</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="name" label=" 姓名">
            <a-input v-model="form.name" :max-length="10" />
          </a-form-model-item>
        </a-col>

        <a-col :span="12">
          <a-form-model-item prop="deptId" label="所属部门">
            <a-tree-select
              v-model="form.deptId"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择部门"
              :load-data="onLoadData"
              :tree-data="deptTreeData"
              :tree-default-expanded-keys="defaultExpandedKeys"
            ></a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="position" label="职务">
            <a-input v-model="form.position" :max-length="20" />
          </a-form-model-item>
        </a-col>

        <a-col :span="12">
          <a-form-model-item prop="isLeader" label="是否为部门负责人">
            <a-select v-model="form.isLeader" :default-value="0">
              <a-select-option :value="1">是</a-select-option>
              <a-select-option :value="0">否</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="roleIds" label="角色">
            <a-select mode="multiple" v-model="form.roleIds" placeholder="请选择角色">
              <a-select-option v-for="role in rolesTreeData" :key="role.roleId">{{role.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="headPortrait" label="头像">
            <ud-upload :length="1" @uploadFile="pictureUpload" :optList="picList" head />
          </a-form-model-item>
        </a-col>
      </a-form-model>
    </a-row>
  </a-modal>
</template>

<script>
import store from 'store'
import upload from '@/components/UpLoad'
import { queryDropdownRoleList, queryCurrentFrontDept, queryUserDetail, addUserInfo, updateUserInfo, queryDeptList } from '@/api/systemPersonnelManage'
import md5 from 'md5'

const defaultForm = () => {
  return {
    account: null, // 是 Stirng  账号
    password: null, //  是 Stirng  密码
    status: 1, //  是 Integer 账号状态
    name: null, //  是 Stirng  姓名
    deptId: null, //  是 Integer 部门ID
    position: null, //  是 Stirng  职务
    isLeader: 0, //  是 Integer 是否为负责人：1是，0否
    roleIds: [], // 是 Stirng  角色id，用”,”隔开
    headPortrait: ''
  }
}

const handleTree = (tree, rspData) => {
  rspData.forEach(v => {
    let t = []
    if (v.childList) {
      handleTree(t, v.childList)
    }
    tree.push({
      title: v.name,
      value: v.deptId,
      key: v.deptId,
      children: t
    })
  })
}
const defaultPh = '默认密码：jiahua123'

export default {
  name: 'development-member',
  props: {
    uiId: [Number, String], // 有值代表编辑
    deptId: [Number, String], // 有值代表创建
    visible: Boolean
  },
  components: {
    'ud-upload': upload
  },
  computed: {
    picList () {
      return this.form.headPortrait ? [this.form.headPortrait] : []
    }
  },
  data () {
    const checkPhone = (rule, value, callback) => {
      if (!Number.isInteger(value - 0)) {
        callback(new Error('请输入11位数字1'))
      } else if ((value + '').length !== 11) {
        callback(new Error('请输入11位数字2'))
      }
      callback()
    }

    return {
      deptMemberOpt: '',
      confirmLoading: false,
      form: defaultForm(),
      defaultExpandedKeys: [],
      deptTreeData: [],
      rolesTreeData: [],
      rules2: {
        // password: [{required: true, message: '密码必须输入', trigger: 'blur'}],
        account: [{ required: true, message: '账号（手机号）必须输入', trigger: 'blur' }, { validator: checkPhone, trigger: 'blur' }],
        name: [{ required: true, message: '姓名必须输入', trigger: 'blur' }],
        position: [{ required: true, message: '职务必须输入', trigger: 'blur' }],
        // headPortrait: [{ required: true, message: '头像必需输入' }],
        status: [{ required: true }],
        isLeader: [{ required: true }],
        deptId: [{ required: true, message: '部门必须选择一个', trigger: ['change', 'blur'] }],
        roleIds: [{ required: true, message: '角色至少选择一个', trigger: ['change', 'blur'] }]
      },
      defaultPh
    }
  },
  methods: {
    handleOk2 (e) {
      this.$refs.ruleForm2.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          let formData = Object.assign({}, this.form, { roleIds: this.form.roleIds.join(',') })
          if (this.uiId) {
            updateUserInfo({ ...formData, uiId: this.uiId }).then(rsp => {
              this.$message.success('更新成员成功！')
              this.$emit('set-visible', false)
              this.$refs['ruleForm2'].resetFields()

              const userId = store.get('userId')
              if (userId - 0 === this.uiId - 0) {
                store.set('headPortrait', formData.headPortrait)
              }
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => {
              this.confirmLoading = false
            })
          } else {
            formData.password = md5('jiahua123')
            addUserInfo(formData).then(rsp => {
              this.$message.success('创建成员成功！')
              this.$emit('set-visible', false)
              this.$refs['ruleForm2'].resetFields()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => {
              this.confirmLoading = false
            })
          }
        }
      })
    },
    handleCancel2 (e) {
      this.$emit('set-visible', false)
      this.$refs['ruleForm2'].resetFields()
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptList({ parentId: treeNode.dataRef.key }).then(rsp => {
          let childrenData = []
          rsp.data.forEach((value) => {
            childrenData.push({
              title: value.name,
              key: value.deptId,
              value: value.deptId
            })
          })
          treeNode.dataRef.children = childrenData
          this.deptTreeData = [...this.deptTreeData]
          resolve()
        })
      })
    },
    pictureUpload (val) {
      this.form.headPortrait = val
    }
  },
  mounted () {
    this.$nextTick(() => {

    })
  },
  watch: {
    visible () {
      if (this.visible) {
        this.deptMemberOpt = this.uiId ? '编辑成员' : '创建成员'

        // 查询角色列表
        queryDropdownRoleList({}).then(rsp => {
          let roles = []
          rsp.data.forEach(v => {
            roles.push(v)
          })
          this.rolesTreeData = roles
        })

        if (this.deptId) {
          this.form.deptId = this.deptId
          queryCurrentFrontDept({ deptId: this.deptId }).then(rsp => {
            let result = rsp.data
            let tree = []
            if (result) {
              handleTree(tree, result)
            }
            this.deptTreeData = [...tree]
            this.defaultExpandedKeys = [this.form.deptId]
          })
        } // 查询部门选择信息 1

        if (this.uiId) {
          queryUserDetail({ uiId: this.uiId }).then(rsp => {
            Object.assign(this.form, rsp.data)

            // 角色选择
            let a = []
            rsp.data.roleList.forEach(v => {
              a.push(v.roleId)
            })
            this.form.roleIds = a

            // 隐藏铭文
            this.defaultPh = '******'

            if (!this.deptId) {
              return rsp.data
            }
          }).then(userDetail => {
            if (!userDetail) return false
            // 查询部门选择信息 2
            queryCurrentFrontDept({ deptId: userDetail.deptId }).then(rsp => {
              let result = rsp.data
              let tree = []
              if (result) {
                handleTree(tree, result)
              }
              this.deptTreeData = [...tree]
              this.defaultExpandedKeys = [userDetail.deptId]
            })
          })
        } else {
          // 新增
          this.defaultPh = defaultPh
          this.form = defaultForm()
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
